package config

import (
	"fmt"
	"log"
	"os"
	"time"

	"github.com/fsnotify/fsnotify"
	"github.com/redis/go-redis/v9"
	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

// 从配置文件读取配置
func initConfig() {
	v := viper.New()
	v.AddConfigPath("./config")
	v.SetConfigType("yaml")
	v.SetConfigName("local")
	if err := v.ReadInConfig(); err != nil {
		fmt.Printf("Error reading config file, %s", err)
		os.Exit(0)
	}

	v.WatchConfig()
	v.OnConfigChange(func(e fsnotify.Event) {
		if e.Has(fsnotify.Write) {
			v.Unmarshal(&GLOBAL_CONFIG)
		}

	})

	v.Unmarshal(&GLOBAL_CONFIG)
}

// 初始化mysql数据库
func initMysql() {
	dsn := GLOBAL_CONFIG.Mysql.Dsn()

	file, err := os.Create("grom-log.txt")
	if err != nil {
		panic("初始化mysql错误，err：" + err.Error())
	}
	fileLogger := log.New(file, "\r\n", log.LstdFlags)

	logLever := logger.Warn
	if GLOBAL_CONFIG.AppDebug {
		logLever = logger.Info
	}

	gormConfig := logger.New(fileLogger, logger.Config{
		SlowThreshold: 2 * time.Second,
		LogLevel:      logLever,
	})
	_db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: gormConfig,
	})
	if err != nil {
		panic("初始化mysql示例错误，err：" + err.Error())
	}

	sqlDb, _ := _db.DB()
	sqlDb.SetMaxIdleConns(5)
	sqlDb.SetMaxOpenConns(20)
	sqlDb.SetConnMaxLifetime(time.Hour)

	DB_MYSQL = _db
}

// 初始化redis
func initRedis() {
	DB_REDIS = redis.NewClient(&redis.Options{
		Addr:     GLOBAL_CONFIG.Redis.Host + ":" + GLOBAL_CONFIG.Redis.Port,
		Password: GLOBAL_CONFIG.Redis.Password,
	})
}

func Init() {
	initConfig()
	initMysql()
	initRedis()
}
